package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.NineGridViewAdapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.ListUser_Information;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.NineGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class GeRen_Update_Msg_PersonPhoto_Activity extends Activity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back;
    private LinearLayout ll_geren_main_update_dzjl, ll_add_photo;
    private String access_token;
    private User_Limit user_limit;
    private TextView tv_feedback_tijiao, tv_geren_update_msg_look_my_yh, tv_geren_update_msg_photo_dianzan;
    private CheckBox cb_register, cb_register1, cb_register2;
    private NineGridView ngv_geren_main_photo;
    private View view;
    public static Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = View.inflate(this, R.layout.activity_geren_update_msg_person_photo, null);
        setContentView(R.layout.activity_geren_update_msg_person_photo);
        activity = this;
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        user_limit = (User_Limit) intent.getSerializableExtra("user_limit");
        back = findViewById(R.id.back);
        ll_geren_main_update_dzjl = findViewById(R.id.ll_geren_main_update_dzjl);
        ll_add_photo = findViewById(R.id.ll_add_photo);
        tv_feedback_tijiao = findViewById(R.id.tv_feedback_tijiao);
        tv_geren_update_msg_look_my_yh = findViewById(R.id.tv_geren_update_msg_look_my_yh);
        tv_geren_update_msg_photo_dianzan = findViewById(R.id.tv_geren_update_msg_photo_dianzan);
        cb_register = findViewById(R.id.cb_register);
        cb_register1 = findViewById(R.id.cb_register1);
        cb_register2 = findViewById(R.id.cb_register2);
        ngv_geren_main_photo = findViewById(R.id.ngv_geren_main_photo);
        back.setOnClickListener(this);
        ll_geren_main_update_dzjl.setOnClickListener(this);
        ll_add_photo.setOnClickListener(this);
        tv_feedback_tijiao.setOnClickListener(this);
        cb_register.setOnClickListener(this);
        cb_register1.setOnClickListener(this);
        cb_register2.setOnClickListener(this);
        tv_geren_update_msg_look_my_yh.setOnClickListener(this);
        JSONObject object = new JSONObject();
        try {
            object.put("uid", user_limit.getUid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postData(object);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_feedback_tijiao:
                SharedPreferences preferences = getSharedPreferences("photo_path", Context.MODE_PRIVATE);
                JSONObject object = new JSONObject();
                //直接用选择的文件URI去展示图片
                //如果所选文件不是图片文件，则展示文件图标
                try{
                    object.put("type", "photo");
                    object.put("path", preferences.getString("path", ""));
                    object.put("p_id", 0);
                    object.put("sort", 1);
                } catch (Exception e){
                    e.printStackTrace();
                }
                postImgData(object);//头像图片获取
                break;
            case R.id.ll_geren_main_update_dzjl:
                Intent intent = new Intent(this, GeRen_Update_Msg_PersonPhoto_DZJiLu_Activity.class);
                intent.putExtra("access_token", access_token);
                startActivity(intent);
                break;
            case R.id.cb_register:
                cb_register.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                cb_register1.setBackgroundResource(R.mipmap.iv_duihao_no);
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_no);
                tv_geren_update_msg_look_my_yh.setVisibility(View.GONE);
                break;
            case R.id.cb_register1:
                cb_register.setBackgroundResource(R.mipmap.iv_duihao_no);
                cb_register1.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_no);
                tv_geren_update_msg_look_my_yh.setVisibility(View.VISIBLE);
                tv_geren_update_msg_look_my_yh.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG );
                break;
            case R.id.cb_register2:
                cb_register.setBackgroundResource(R.mipmap.iv_duihao_no);
                cb_register1.setBackgroundResource(R.mipmap.iv_duihao_no);
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                tv_geren_update_msg_look_my_yh.setVisibility(View.GONE);
                break;
            case R.id.tv_geren_update_msg_look_my_yh:
                Intent intent1 = new Intent(this, GeRen_Update_Photo_Look_Activity.class);
                intent1.putExtra("access_token", access_token);
                startActivity(intent1);
                break;
            case R.id.ll_add_photo:
                Intent intent2 = new Intent(this, PhotoAlbum_Activity.class);
                intent2.putExtra("access_token", access_token);
                intent2.putExtra("bucket", "photo");
                intent2.putExtra("cos_type", 0);
                startActivity(intent2);
                break;
            case R.id.back:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_fans_cancle)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        JSONObject object = new JSONObject();
        try {
            object.put("uid", user_limit.getUid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postData(object);
    }

    @Override
    protected void onResume() {
        super.onResume();
        onCreate(null);
    }

    public void refresh() {
        onCreate(null);
    }

    /**
     * 网络请求
     */
    private void postData(JSONObject object) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.tr_user_information_photo_Url + access_token, object, new Response.Listener<JSONObject>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        int is_support = info.getInt("is_support");
                        int photoStatus = info.getInt("photoStatus");
                        int photoHots = info.getInt("photoHots");
                        JSONArray files = info.getJSONArray("files");
                        List<ListUser_Information.Files> user_informations = gson.fromJson(files.toString(), new TypeToken<List<ListUser_Information.Files>>(){}.getType());
                        if (user_informations.size() == 9){
                            ll_add_photo.setVisibility(View.GONE);
                            ngv_geren_main_photo.setVisibility(View.VISIBLE);
                        } else if (9 > user_informations.size() && user_informations.size() > 0){
                            ll_add_photo.setVisibility(View.VISIBLE);
                            ngv_geren_main_photo.setVisibility(View.VISIBLE);
                        } else {
                            ll_add_photo.setVisibility(View.VISIBLE);
                            ngv_geren_main_photo.setVisibility(View.GONE);
                        }
                        NineGridViewAdapter adapter = new NineGridViewAdapter(GeRen_Update_Msg_PersonPhoto_Activity.this, user_informations, access_token);
                        adapter.setImageInfoList(user_informations);
                        ngv_geren_main_photo.setSingleImageSize(254);
                        ngv_geren_main_photo.setSingleImageRatio(1);
                        ngv_geren_main_photo.setGridSpacing(2);
                        ngv_geren_main_photo.setMaxSize(user_informations.size());
                        ngv_geren_main_photo.setAdapter(adapter);
                        tv_geren_update_msg_photo_dianzan.setText("" + photoHots);
                    } else {
                        ToolUtils.showToast(GeRen_Update_Msg_PersonPhoto_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Update_Msg_PersonPhoto_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     * @param object
     */
    private void postImgData(JSONObject object) {
        Log.d("fill_information", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.fill_information_icon_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("fill_information", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        String path = info.getString("path");//图片cos访问地址
                        ToolUtils.showToast(GeRen_Update_Msg_PersonPhoto_Activity.this, message);
                        finish();
                    } else {
                        ToolUtils.showToast(GeRen_Update_Msg_PersonPhoto_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRen_Update_Msg_PersonPhoto_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @SuppressLint({"NonConstantResourceId", "SetTextI18n"})
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_fans_cancle:
                TextView tv_cancle = view.findViewById(R.id.tv_cancle);
                TextView tv_geren_fans_cancle = view.findViewById(R.id.tv_geren_fans_cancle);
                TextView img_guanbi = view.findViewById(R.id.img_guanbi);
                tv_geren_fans_cancle.setText("是否放弃对资料的修改");
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        finish();
                    }
                });
                img_guanbi.setText("继续编辑");
                img_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            CommonPopWindow.newBuilder()
                    .setView(R.layout.pop_geren_fans_cancle)
                    .setAnimationStyle(R.style.AnimUp)
                    .setBackgroundDrawable(new BitmapDrawable())
                    .setSize(0, 600)
                    .setViewOnClickListener(this)
                    .setBackgroundDarkEnable(true)
                    .setBackgroundAlpha(0.7f)
                    .build(this)
                    .showAsCenter(view);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
